// 环境配置（从 MerchantApp 迁移，H5 环境兼容）
const defaultConfig = { VUE_APP_BASE_API: 'http://localhost:6000', VUE_APP_WS_URL: 'wss://ws.oceanbridge.com', VUE_APP_UPLOAD_URL: 'https://upload.oceanbridge.com', VUE_APP_CDN_URL: 'https://cdn.oceanbridge.com', VUE_APP_ENV: 'production', VUE_APP_MOCK_ENABLED: false, VUE_APP_DEBUG: false, VUE_APP_LOG_LEVEL: 'error' }
const developmentConfig = { VUE_APP_BASE_API: 'http://localhost:6000', VUE_APP_WS_URL: 'ws://localhost:6000', VUE_APP_UPLOAD_URL: 'http://localhost:6000', VUE_APP_CDN_URL: 'http://localhost:6000', VUE_APP_ENV: 'development', VUE_APP_MOCK_ENABLED: false, VUE_APP_DEBUG: true, VUE_APP_LOG_LEVEL: 'debug' }
const testConfig = { VUE_APP_BASE_API: 'https://test-api.oceanbridge.com', VUE_APP_WS_URL: 'wss://test-ws.oceanbridge.com', VUE_APP_UPLOAD_URL: 'https://test-upload.oceanbridge.com', VUE_APP_CDN_URL: 'https://test-cdn.oceanbridge.com', VUE_APP_ENV: 'test', VUE_APP_MOCK_ENABLED: false, VUE_APP_DEBUG: true, VUE_APP_LOG_LEVEL: 'info' }

function getCurrentEnvironment(){
  if (typeof window !== 'undefined'){
    const urlParams = new URLSearchParams(window.location.search)
    const env = urlParams.get('env') || localStorage.getItem('app_env') || import.meta.env.MODE
    if (env) return env
  }
  if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV){ return process.env.NODE_ENV }
  return 'development'
}

function getEnvConfig(){
  const env = getCurrentEnvironment()
  let config = { ...defaultConfig }
  switch(env){
    case 'development': config = { ...config, ...developmentConfig }; break
    case 'test': config = { ...config, ...testConfig }; break
    case 'production':
    default: break
  }
  try { const local = JSON.parse(localStorage.getItem('env_config')||'null'); if (local && typeof local==='object'){ config = { ...config, ...local } } } catch(e){ console.warn('读取本地环境配置失败:', e) }
  return config
}

function setEnvConfig(newConfig){ try { const merged = { ...getEnvConfig(), ...newConfig }; localStorage.setItem('env_config', JSON.stringify(merged)); return true } catch(e){ console.error('设置环境配置失败:', e); return false } }

function getEnv(key, def=null){ const c = getEnvConfig(); return c[key] !== undefined ? c[key] : def }
function isDevelopment(){ return getCurrentEnvironment() === 'development' }
function isProduction(){ return getCurrentEnvironment() === 'production' }
function isTest(){ return getCurrentEnvironment() === 'test' }
function isDebug(){ return getEnv('VUE_APP_DEBUG', false) }
function isMockEnabled(){ return getEnv('VUE_APP_MOCK_ENABLED', false) }

export default { getEnvConfig, setEnvConfig, getEnv, getCurrentEnvironment, isDevelopment, isProduction, isTest, isDebug, isMockEnabled }
export { getEnvConfig, setEnvConfig, getEnv, getCurrentEnvironment, isDevelopment, isProduction, isTest, isDebug, isMockEnabled }

